package demo.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jweb.core.bean.PageMode;
import org.jweb.core.bean.ReplyDataMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.ResourceUtil;
import org.jweb.core.util.StringUtil;
import org.jweb.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.keepme.ep.auth.transfer.vo.authen.AuthUserVO;
import cn.keepme.ep.auth.transfer.vo.authen.UserCategoryTradeVO;
import cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO;
import cn.keepme.ep.common.entity.DictType;
import cn.keepme.ep.common.service.SMSServiceI;
import cn.keepme.ep.common.service.SysServiceI;
import cn.keepme.ep.member.entity.UserCategoryEntity;
import cn.keepme.ep.member.entity.UserCategoryTradeEntity;
import cn.keepme.ep.member.transfer.form.member.UserCategorySearchForm;
import cn.keepme.ep.member.transfer.form.member.UserCategoryTradeSearchForm;
import cn.keepme.ep.util.CommonMethod;

import com.alibaba.fastjson.JSON;

import demo.entity.AcquiDataEntity;
import demo.entity.AnalyzeMsgEntity;
import demo.entity.AnalyzeRoomEntity;
import demo.entity.AnalyzeTradeEntity;
import demo.trans.form.AnalyzeRoomSearchForm;
import demo.trans.form.HallMsgSearchForm;
import demo.trans.form.RoomMsgSearchForm;
import demo.trans.vo.AnalyzeTradeVo;
import demo.trans.vo.HallMsgVO;
import demo.util.DataAcquisitionConvert;
import demo.util.UUIDGenerator;

@Controller
@RequestMapping("/hall")
public class HallController extends BaseController{
	@Autowired
	private SysServiceI sysService;
	@Autowired
	private SMSServiceI smsService;
	
	/**
	  * 价格换算
	  */
	@RequestMapping(value = "/dataConvert")
	@ResponseBody
	public ReplyDataMode dataConvert(String content,String msgRoomId,String roomName, 
			HttpServletRequest request, HttpServletResponse response) {
		ReplyDataMode j = new ReplyDataMode();
		String tradeName = getTradeName();
		content = DataAcquisitionConvert.execConvert(content,msgRoomId,roomName, sysService, tradeName);
		j.setData(content);
		j.setSuccess(true);
		return j;
	}
	
	/**
	 * 接盘大厅消息列表 new
	 * 
	 * @return
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = "/msgList2")
	@ResponseBody
	public ReplyDataMode msgList2(RoomMsgSearchForm searchForm, HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		ReplyDataMode j = new ReplyDataMode();
		String roomId = "";
		String tradeName = getTradeName();
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
		// 查用户预先设置的交易所品种
		if(userInfo != null){
			// 1.登陆用户
			roomId = getRoomIdForUserInfo(userInfo);
		}else{
			AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
			if(userInfoTmp != null ){
				// 2.非登陆用户,从临时用户中查
				roomId = getRoomIdForUserInfoTmp(userInfoTmp);
			}else{
				// 进hall.html 选交易所
//				request.getRequestDispatcher("tpartner-wx/webpage/index.html").forward(request, response);
//				String uri = request.getRequestURI();
//				String url = request.getRequestURL().toString();
//				String path = url.substring(0, url.indexOf(uri));
//				String res = path +"/tpartner-wx/webpage/index.html";
//				response.sendRedirect(res);
			}
		}
		// 判断roomid 为空则不查询
		if("".equals(roomId)){
			j.setSuccess(true);
			return j;
		}
		searchForm.setRoomId(roomId);  // 加入品种房间 筛选条件
		
		/**时间范围计算开始*/
		//获取发布时间范围，单位天，查询从当前时间推后该时间起到现在时间范围内的消息数据，防止全库查询，导致数据过多
		String publicTimeRang = ResourceUtil.getConfigByName("hall_msg_public_time_rang");
		long timeRang = Long.parseLong(publicTimeRang);
		timeRang = timeRang*24*60*60*1000;
		long curTime = System.currentTimeMillis();
		long startTime = curTime - timeRang;
		Date startPublishTime = new Date(startTime);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String startPublishTimeStr = format.format(startPublishTime);
		searchForm.setPublishTimeBegin(startPublishTimeStr);
		searchForm.emptyValue2NullValue();
		/**时间范围计算结束*/
//		searchForm.setRoomId("402881ea4fc09bed014fc0b26e9b0008,402881ea4fc09bed014fc0b66a42000b");
		
		searchForm.emptyValue2NullValue();
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		
		Map<String,Object> orderMap = new HashMap<String,Object>();
		orderMap.put("publishTime", "asc");
		cq.setOrder(orderMap);
		int pageSize = Integer.parseInt(searchForm.getPageSize());
		int pageNo = Integer.parseInt(searchForm.getPageNo());
//		int pageNo = 9;
//		System.out.println("###pageNo="+pageNo);
		
		// 分页问题，已修改，by wupan
//		PageMode page = this.sysService.list4page(cq, pageSize,pageNo);
		PageMode page = this.sysService.list4page(cq, pageNo, pageSize);
		
		List<AnalyzeMsgEntity> entityList = page.getResult();
		List<HallMsgVO> voList = new ArrayList<HallMsgVO>();
		SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
		HallMsgVO vo = null;
		for(AnalyzeMsgEntity e : entityList){
			/** add by wupan on 20151216 start 	**/
			String content = e.getContent();
			String msgRoomId = e.getAnalyzeRoom().getId();
			String roomName = e.getAnalyzeRoom().getName();
			content = DataAcquisitionConvert.execConvert(content,msgRoomId,roomName, sysService, tradeName);
			e.setContent(content);
			/** add by wupan on 20151216 end  **/
			vo = new HallMsgVO();
			vo.copyEntity(e);
			vo.setPublishDate(format2.format(e.getPublishTime()));
			voList.add(vo);
		}
		
		page.setResult(voList);
		
		j.setData(page);
		j.setSuccess(true);
		return j;
	}
	
	/**
	 * 获取 临时用户 预先设置的交易所品种
	 * @return
	 */
	private String getRoomIdForUserInfoTmp(AuthUserVO userInfoTmp){
		String roomid = "";
		List<UserCategoryTradeVO> ulist = CommonMethod.getTmpUserInfo(this.sysService, userInfoTmp.getId());
		StringBuffer notifyCategoryArrStr = new StringBuffer();
		for(UserCategoryTradeVO c : ulist){
			if("1".equals(c.getStatus())){
				notifyCategoryArrStr.append(c.getRoomid()).append(",");
			}
		}
		if(notifyCategoryArrStr.length() > 0){
			roomid = notifyCategoryArrStr.deleteCharAt(notifyCategoryArrStr.length()-1).toString();
			// 根据code 查 roomid (不需要再查数据，getSession()中存在)
			// roomid = getAnalyzeRoomid(notifyCategoryArrStr.toString());
		}
		return roomid;
	}
	/**
	 * 获取 临时用户 预先设置的交易所品种
	 * @return
	 */
	private String getRoomIdForUserInfo(AuthUserVO userEntity){
		String roomid = "";
//		List<com.crinser.tp.auth.transfer.vo.authen.UserCategoryVO> ulist = CommonMethod.getUserInfo(this.sysService,userEntity.getMphone());
		List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO> ulist = CommonMethod.getUserInfo(this.sysService,userEntity.getId());
		StringBuffer notifyCategoryArrStr = new StringBuffer();
		for(UserCategoryVO c : ulist){
			if("1".equals(c.getStatus())){
				notifyCategoryArrStr.append(c.getRoomid()).append(",");
			}
		}
		if(notifyCategoryArrStr.length() > 0){
			roomid = notifyCategoryArrStr.deleteCharAt(notifyCategoryArrStr.length()-1).toString();
			// 根据code 查 roomid (不需要再查数据，getSession()中存在)
			// roomid = getAnalyzeRoomid(notifyCategoryArrStr.toString());
		}
		return roomid;
	}
	
	private String getTradeName(){
		String tradeName = "";
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
		AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
		if(userInfo == null && userInfoTmp == null ){
			
		}else{
			if(userInfo != null ){
				String userId = userInfo.getId();
				// 执行查询 （根据交易所id查 交易所）
				List<UserCategoryEntity> userCategoryList  = sysService.findByProperty(UserCategoryEntity.class, "generalUserId", userId);
				tradeName = userCategoryList.get(0).getTradeName();
			}else if(userInfoTmp != null ){
				tradeName = userInfoTmp.getTradeName();
			}
		}
		return tradeName;
	}
	
	/**
	 * 获取 登陆用户 预先设置的交易所品种
	 * @return
	 */
	private String getRoomIdForUserInfo_bak(AuthUserVO userEntity){
		String roomid = "";
		List<UserCategoryVO> ulist = getNotifySetingInfo(userEntity.getId());
		StringBuffer notifyCategoryArrStr = new StringBuffer();
		for(UserCategoryVO c : ulist){
			if("1".equals(c.getStatus())){
				notifyCategoryArrStr.append(c.getCode()).append(",") ;
			}
		}
		if(notifyCategoryArrStr.length() > 0){
			notifyCategoryArrStr.deleteCharAt(notifyCategoryArrStr.length()-1);
			// 根据code 查 roomid
			roomid = getAnalyzeRoomid(notifyCategoryArrStr.toString());
		}
		return roomid;
	}
	private List<UserCategoryVO> getNotifySetingInfo(String userId){
		//获交易类型取数据字典
		List<DictType> tradeTypeDictTypeList = this.sysService.findDict("custom");
		Map<String,DictType> tradeTypeDictTypeMap = new HashMap<String,DictType>();
		for(DictType d : tradeTypeDictTypeList){
			tradeTypeDictTypeMap.put(d.getTypecode(), d);
		}
		
		UserCategorySearchForm searchForm = new UserCategorySearchForm();
		searchForm.setUserId(userId);
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
		
		List<UserCategoryVO> ulist = new ArrayList<UserCategoryVO>();
		for(UserCategoryEntity c : userCategoryList){
			UserCategoryVO vo = new UserCategoryVO();
//			vo.setStatus(c.getStatus());
			vo.setStatus(c.getTradeRoomIdStatus());
			vo.setCode(c.getCategoryCode());
			String code = c.getCategoryCode();
			if(StringUtil.isNotEmpty(code)){
				DictType temp = tradeTypeDictTypeMap.get(code);
				if(temp != null){
					vo.setName(temp.getTypename());
				}
			}
			ulist.add(vo);
		}
		return ulist;
	}
	private String getAnalyzeRoomid(String code){
		AnalyzeRoomSearchForm searchForm = new AnalyzeRoomSearchForm();
		searchForm.setCode(code);
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		List<AnalyzeRoomEntity> ulist = this.sysService.list(cq);
		StringBuffer sb = new StringBuffer();
		for(AnalyzeRoomEntity c : ulist){
				sb.append(c.getId()).append(",") ;

		}
		if(sb.length() > 0){
			sb.deleteCharAt(sb.length()-1);
		}
		return sb.toString();
	}
	
	/**
	 * 创建临时用户
	 * @param tradeId
	 * @param uuid
	 */
	private void setUserInfoTmp(String tradeId,String uuid){
		String tradeName = "";
		String tradeRoomId = "";
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
		AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
		
		if(userInfo == null && userInfoTmp == null ){
			
			// 创建临时用户
			UserCategoryTradeEntity ucEntity = null;
//			String sql = "select t1.id,t1.category_code from tp_analyze_category t1 where t1.parent_category_id is not null";
			String sql = "select t2.id as roomid,t1.category_code,t1.id as category_id from tp_analyze_category t1,tp_analyze_room t2 where t1.parent_category_id is not null and t1.id=t2.category_code "
					+ "and t1.`status`='1' and t2.`status`='1'";
			List<String[]> ucList = this.sysService.findListbySql(sql);
			for (Object obj : ucList) {
				Object[] u = (Object[]) obj;
				ucEntity = new UserCategoryTradeEntity();
				
				ucEntity.setTmpUserId(uuid);
				ucEntity.setTradeId(tradeId);
				
				AnalyzeTradeEntity entity = getAnalyzeTradeEntity(tradeId);
				tradeName = entity.getTradeName();
				ucEntity.setTradeName(tradeName);
//				tradeRoomId = entity.getRoomId();
//				ucEntity.setTradeRoomId(tradeRoomId);
				
				ucEntity.setTradeRoomId(u[0].toString());
				ucEntity.setCategoryCode(u[1].toString());
				ucEntity.setCategoryId(u[2].toString());
				ucEntity.setTradeRoomIdStatus("0"); // 默认都不选中
				this.sysService.saveOrUpdate(ucEntity);
			}
			//设置新的临时用户缓存信息
			AuthUserVO user = new AuthUserVO();
			List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryTradeVO> ulist = CommonMethod.getTmpUserInfo(this.sysService, uuid);
			user.setId(uuid);
			user.setTmpulist(ulist);
			user.setTradeName(tradeName);
			currentUser.getSession().setAttribute("userInfoTmp", user);
		
		}else{
			// 用户登陆
			if(userInfo != null){
				// 取用户预配置品种
				String userid = userInfo.getId();
//				String userid = userInfo.getMphone();
//				System.out.println("####userid = "+userid);
				
				// 查临时用户是否存在，避免重复创建
				String sql0 = "select count(*) from tp_user_category where general_user_id ='"+userid+"'";
				List<String> ucListCount = this.sysService.findListbySql(sql0);
				for(Object obj : ucListCount){
					Object u = (Object) obj;
//					System.out.println("#### "+ u.toString()+ " #### "+sql0);
					if(!"0".equals(u.toString())){  // 非0条记录 说明已创建该用户
//						return;
						// 更新该用户信息（假设用户之前已选择交易所A 现切换交易所B 用交易所B覆盖交易所A ）
						UserCategorySearchForm searchForm = new UserCategorySearchForm();
						searchForm.setUserId(userid);
						CriteriaQuery cq = searchForm.getCriteriaQuery();
						List<UserCategoryEntity> userCategoryList = this.sysService.list(cq);
//						System.out.println("#### userCategoryList -"+ userCategoryList.get(0).toString());
						//如果用户是初次设置，则初始化用户设置
						if(userCategoryList.isEmpty()){
							
						} else {
//							UserCategoryTradeEntity userCategory = userCategoryList.get(0);
							for(UserCategoryEntity ucEntity:userCategoryList){
								ucEntity.setTradeId(tradeId);
								AnalyzeTradeEntity entity = getAnalyzeTradeEntity(tradeId);
								tradeName = entity.getTradeName();
								tradeRoomId = getAnalyzeTradeRoomId(ucEntity.getCategoryCode());
								ucEntity.setTradeName(tradeName);
								ucEntity.setTradeRoomId(tradeRoomId);
								ucEntity.setTradeName(tradeName);
								ucEntity.setTradeRoomIdStatus("0");  // 修改交易所品种对应房间 有效状态 全部初始化
								this.sysService.saveOrUpdate(ucEntity);
							}
						}
						
						//更新当前会话中缓存的 临时用户信息
						AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");
						List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryVO> ulist = CommonMethod.getUserInfo(this.sysService, userid);
						user.setUlist(ulist);
						user.setTradeName(tradeName);
						currentUser.getSession().setAttribute("userInfo", user);
						return;
					}
				}
			}
			
			else
			{
//				userInfo == null && userInfoTmp != null
				// 更新临时用户缓存
				// 查临时用户是否存在，避免重复创建
				String sql0 = "select count(*) from tp_user_category_trade where tmp_user_id ='"+uuid+"'";
				List<String> ucListCount = this.sysService.findListbySql(sql0);
				for(Object obj : ucListCount){
					Object u = (Object) obj;
					System.out.println(u.toString());
					if(!"0".equals(u.toString())){  // 非0条记录 说明已创建该用户
//						return;
						// 更新该用户信息（假设用户之前已选择交易所A 现切换交易所B 用交易所B覆盖交易所A ）
						UserCategoryTradeSearchForm searchForm = new UserCategoryTradeSearchForm();
						searchForm.setUserId(uuid);
						CriteriaQuery cq = searchForm.getCriteriaQuery();
						List<UserCategoryTradeEntity> userCategoryList = this.sysService.list(cq);
						
						//如果用户是初次设置，则初始化用户设置
						if(userCategoryList.isEmpty()){
							
						} else {
//							UserCategoryTradeEntity userCategory = userCategoryList.get(0);
							for(UserCategoryTradeEntity ucEntity:userCategoryList){
								ucEntity.setTradeId(tradeId);
								AnalyzeTradeEntity entity = getAnalyzeTradeEntity(tradeId);
								tradeName = entity.getTradeName();
								ucEntity.setTradeName(tradeName);
//								tradeRoomId = entity.getRoomId();
//								ucEntity.setTradeRoomId(tradeRoomId);
								ucEntity.setTradeRoomIdStatus("0");  // 修改交易所品种对应房间 有效状态 全部初始化
								this.sysService.saveOrUpdate(ucEntity);
							}
						}
						
						//更新当前会话中缓存的 临时用户信息
						AuthUserVO user = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");
						List<cn.keepme.ep.auth.transfer.vo.authen.UserCategoryTradeVO> ulist = CommonMethod.getTmpUserInfo(this.sysService,userInfoTmp.getId());
						user.setTmpulist(ulist);
						user.setTradeName(tradeName);
						currentUser.getSession().setAttribute("userInfoTmp", user);
						return;
					}
				}
			}
			
		}
	}
	
	/**
	 * 查询分页信息，为界面提供总页数，总记录数等信息，方便页面做决策
	 * @param searchForm
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/msgPageInfo")
	@ResponseBody
	public ReplyDataMode msgPageInfo(HallMsgSearchForm searchForm,HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		CriteriaQuery cq = searchForm.getCriteriaQuery();
		int pageSize = Integer.parseInt(searchForm.getPageSize());
		int pageNo = Integer.parseInt(searchForm.getPageNo());
//		PageMode page = this.sysService.list4page(cq, pageSize,pageNo);
		PageMode page = this.sysService.list4page(cq, pageNo, pageSize);
		
		page.setResult(null);//只保留分页信息，分页列表信息不要
		
		j.setData(page);
		j.setSuccess(true);
		return j;
	}
	
	
	
	/**
	 * 交易所列表
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/tradeList")
	@ResponseBody
	public ReplyDataMode tradeList(HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		
		// 执行查询 hql 查所有交易所
		String hql = "from AnalyzeTradeEntity where parentCategory is null";
		List<AnalyzeTradeEntity> entityList = sysService.findByQueryString(hql);
		List<AnalyzeTradeVo> voList = new ArrayList<AnalyzeTradeVo>();
		AnalyzeTradeVo vo = null;
		for(AnalyzeTradeEntity e : entityList){
			vo = new AnalyzeTradeVo();
			vo.copyEntity(e);
			voList.add(vo);
		}
		
		j.setData(voList);
		j.setSuccess(true);
		return j;
	}
	
	/**
	 * 交易所列表
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/tradeHList")
	@ResponseBody
	public ReplyDataMode tradeHList(HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		String uuid = new UUIDGenerator().getUUID();
		
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
		AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
		
		// 执行查询 hql 查所有交易所
		String hql = "from AnalyzeTradeEntity where parentCategory is null";
		List<AnalyzeTradeEntity> entityList = sysService.findByQueryString(hql);

		List<Map> mapList = new ArrayList<Map>();
		Map map = null;
		String url = "";
		for(AnalyzeTradeEntity e : entityList){
			map=new HashMap();
			map.put("text", e.getTradeName());

			// 判断 登陆/临时缓存 用户 传递不同用户id
			if(userInfo != null){
				// 获取userInfo中的 userInfo.getId()
				url = "hall-info.html?tradeId="+e.getId()+"&uuid="+userInfo.getId(); 
			}else{
				if(userInfoTmp != null){
					url = "hall-info.html?tradeId="+e.getId()+"&uuid="+userInfoTmp.getId(); 
				}else{
					// 创建一个uuid
					url = "hall-info.html?tradeId="+e.getId()+"&uuid="+uuid; 					
				}
			}
			map.put("href", url);
			mapList.add(map);
		}
		// <a href='http://127.0.0.1/tpartner-wx/hall/tradeCategoryList.do?id="+ data[i].id+"'>"+data[i].tradeName+"</a>" + "</h4></div><br />
		Map resultMap = new HashMap();
		resultMap.put("list", mapList);
		Object obj = JSON.toJSON(resultMap);
		
		j.setData(obj);
		j.setSuccess(true);
		return j;
	}
	
	@RequestMapping(value = "/tradeCategoryList")
	@ResponseBody
	public ReplyDataMode tradeCategoryList(String tradeId,String uuid,HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();

		setUserInfoTmp(tradeId, uuid);  // 进入关键方法，创建临时用户
		
		// 执行查询 （根据交易所id查 交易所）
		AnalyzeTradeEntity entity = (AnalyzeTradeEntity)sysService.findUniqueByProperty(AnalyzeTradeEntity.class, "id", tradeId);
		
		// 执行查询 （根据交易所id查 交易所其下品种）
		String sql = "select room_id, trade_name  from tp_analyze_trade where parent_category_id='"+tradeId+"' and status='1'";
		List<String[]> entityList =this.sysService.findListbySql(sql);

		List<Map> varietymapList = new ArrayList<Map>();
		Map map = null;
		for(int  i=0;  i<entityList.size();    i++)    {
			Object  e[]    =    entityList.get(i);
//			System.out.println(e[1]);
			map=new HashMap();
			map.put("name", e[0]);  // roomid 
			map.put("text", e[1]);  	//   品种名称 tradeName
			varietymapList.add(map);
		}   
		// 执行查询（根据交易所id查 总品种里非交易所的其他品种）
		String sql2 = "select id, category_name  from tp_analyze_category where parent_category_id is not null and category_name "
				+ "not in (select trade_category from tp_analyze_trade where parent_category_id='"+ tradeId+"') and status='1'";
		List<String[]> entityList2 =this.sysService.findListbySql(sql2);
		
		List<Map> exchangemapList = new ArrayList<Map>();
		map = null;
		for(int  i=0;  i<entityList2.size();    i++)    {
			Object  e[]    =    entityList2.get(i);
//			System.out.println(e[1]);
			map=new HashMap();
			map.put("name", e[0]);  // id 
			map.put("text", e[1]);     // 品种名称 categoryName
			exchangemapList.add(map);
		}
		
		Map resultMap = new HashMap();
		resultMap.put("trade", entity.getTradeName());
		resultMap.put("variety", varietymapList);
		resultMap.put("exchange", exchangemapList);
		Object obj = JSON.toJSON(resultMap);
		
		j.setData(obj);
		j.setSuccess(true);
		
//		System.out.println("uuid="+uuid);
		
		return j;
	}
	
	
	@RequestMapping(value = "/getTradeNameHeadTitle")
	@ResponseBody
	public ReplyDataMode getTradeName(HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		String userId = "";
		String tradeName = "";
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
		AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
		if(userInfo == null && userInfoTmp == null ){
			
		}else{
			if(userInfo != null ){
				userId = userInfo.getId();
				// 执行查询 （根据交易所id查 交易所）
//		AnalyzeTradeEntity entity = (AnalyzeTradeEntity)sysService.findUniqueByProperty(AnalyzeTradeEntity.class, "id", tradeId);
				List<UserCategoryEntity> userCategoryList  = sysService.findByProperty(UserCategoryEntity.class, "generalUserId", userId);
				tradeName = userCategoryList.get(0).getTradeName();
//				tradeName = userInfo.getTradeName();
			}else if(userInfoTmp != null ){
//				tradeId = userInfoTmp.getTmpulist().get(0).getTradeid();
				tradeName = userInfoTmp.getTradeName();
			}
		}
		j.setData(tradeName);
		j.setSuccess(true);

		return j;
	}
/*
	public String getTradeNameById(String tradeId){
		// 执行查询 （根据交易所id查 交易所）
		AnalyzeTradeEntity entity = (AnalyzeTradeEntity)sysService.findUniqueByProperty(AnalyzeTradeEntity.class, "id", tradeId);
		String tradeName = entity.getTradeName();
		return tradeName;
	}
*/
	public AnalyzeTradeEntity getAnalyzeTradeEntity(String tradeId){
		// 执行查询 （根据交易所id查 交易所）
		AnalyzeTradeEntity entity = (AnalyzeTradeEntity)sysService.findUniqueByProperty(AnalyzeTradeEntity.class, "id", tradeId);
		return entity;
	}
	public String getAnalyzeTradeRoomId(String categoryCode){
		String roomid = "";
		String sql = "select t2.id as roomid from tp_analyze_category t1,tp_analyze_room t2 where t1.id=t2.category_code and t1.category_code='"+categoryCode+ "'";
		List<String> ucList = this.sysService.findListbySql(sql);
		for (Object obj : ucList) {
			String u =  (String) obj;
			roomid = u;
		}
		return roomid;
	}
	
	public static final String unescapeStr(String str,String regex, String replacement) {
	     if (isNullValue(str))
	       return "";
	     str = str.replaceAll(regex, replacement);
	     return str;
	   }
	
	 public static boolean isNullValue(String value)
	   {
	     return (value == null) || (value.trim().equals(""));
	   }
	 
	 /**
	  * 判断交易所品种是否有被选中
	  * @param roomid
	  * @param req
	  * @return
	  */
	@RequestMapping(value = "/isSelectedCategory")
	@ResponseBody
	public ReplyDataMode isSelectedCategory(String userid, HttpServletRequest req){
		ReplyDataMode j = new ReplyDataMode();
		// 判断用户
		Subject currentUser = SecurityUtils.getSubject();
		AuthUserVO userInfo = (AuthUserVO)currentUser.getSession().getAttribute("userInfo");   // 登陆用户
		AuthUserVO userInfoTmp = (AuthUserVO)currentUser.getSession().getAttribute("userInfoTmp");  // 临时用户
		String sql0 = "";
		if(userInfo == null && userInfoTmp == null ){
			
		}
		else if(userInfo != null){
			// 用户登陆
			sql0 = "select count(*) from tp_user_category where general_user_id = '"+userid+"' and trade_room_id_status = '1';";
		}
		else if(userInfoTmp != null){
			// 用户登陆
			sql0 = "select count(*) from tp_user_category_trade where tmp_user_id = '"+userid+"' and trade_room_id_status = '1';";			
		}
		// 查临时用户是否存在，避免重复创建
		List<String> ucListCount = this.sysService.findListbySql(sql0);
		for(Object obj : ucListCount){
			Object u = (Object) obj;
			System.out.println(u.toString());
			if(!"0".equals(u.toString())){
				j.setSuccess(true);
			}else{
				j.setSuccess(false);
			}
		}
		return j;
	}
	 
	 

		/**
		 * 接盘大厅消息列表
		 * @param searchForm
		 * @param req
		 * @return
		 */
		@RequestMapping(value = "/msgList")
		@ResponseBody
		public ReplyDataMode msgList(HallMsgSearchForm searchForm,HttpServletRequest req){
			ReplyDataMode j = new ReplyDataMode();
			
			/**时间范围计算开始*/
			//获取发布时间范围，单位天，查询从当前时间推后该时间起到现在时间范围内的消息数据，防止全库查询，导致数据过多
			String publicTimeRang = ResourceUtil.getConfigByName("hall_msg_public_time_rang");
			long timeRang = Long.parseLong(publicTimeRang);
			timeRang = timeRang*24*60*60*1000;
			long curTime = System.currentTimeMillis();
			long startTime = curTime - timeRang;
			Date startPublishTime = new Date(startTime);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startPublishTimeStr = format.format(startPublishTime);
			searchForm.setPublishTimeBegin(startPublishTimeStr);
			searchForm.emptyValue2NullValue();
			/**时间范围计算结束*/
			
			CriteriaQuery cq = searchForm.getCriteriaQuery();
			Map<String,Object> orderMap = new HashMap<String,Object>();
			orderMap.put("publishTime", "asc");
			cq.setOrder(orderMap);
			int pageSize = Integer.parseInt(searchForm.getPageSize());
			int pageNo = Integer.parseInt(searchForm.getPageNo());
//			int pageNo = 9;
//			System.out.println("###pageNo="+pageNo);
			
			// 分页问题，已修改，by wupan
//			PageMode page = this.sysService.list4page(cq, pageSize,pageNo);
			PageMode page = this.sysService.list4page(cq, pageNo, pageSize);
			
			List<AnalyzeMsgEntity> entityList = page.getResult();
			List<HallMsgVO> voList = new ArrayList<HallMsgVO>();
			SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
			HallMsgVO vo = null;
			for(AnalyzeMsgEntity e : entityList){
				vo = new HallMsgVO();
				vo.copyEntity(e);
				vo.setPublishDate(format2.format(e.getPublishTime()));
				voList.add(vo);
			}
			
			page.setResult(voList);
			
			j.setData(page);
			j.setSuccess(true);
			return j;
		}
		
		
		
		
}
